package cn.ejopenai.core;

import cn.ejopenai.domain.MessageObject;
import cn.ejopenai.domain.RequestObject;
import cn.ejopenai.domain.ResultMessage;
import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * author ： willie
 */
public class OpenAIService {
    private final String URL = "https://api.openai.com/v1/chat/completions";
    private final String DEFAULT_MODEL = "gpt-3.5-turbo";
    private String apiKey;
    private static final List<ResultMessage> allMessage = new ArrayList<>();

    public OpenAIService(String apiKey){
        this.apiKey = apiKey;
    }


    public ResponseResult sendRequest(RequestHandler requestHandler) {
        try {
            // 创建 HTTP 的 post 请求
            URL obj = new URL(URL);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "Bearer " + this.apiKey);
            conn.setRequestProperty("Content-Type", "application/json");

            // 请求体封装
            String body = getRequestBodyString(requestHandler);
            System.out.println(body);

            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(body);
            writer.flush();
            writer.close();

            // 获取响应
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String outLine;
            StringBuffer response = new StringBuffer();
            while ((outLine = br.readLine()) != null) {
                response.append(outLine);
            }
            br.close();

            // 封装请求体和本次结果消息
            return responseHandler(requestHandler,response);


        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }



    private ResponseResult responseHandler(RequestHandler requestHandler,StringBuffer response) {
        // 响应数据获取
        String rawResult = response.toString();
        String singleResult = response.toString().split("\"content\": \"")[1].split("\"")[0];

        // 封装结果数据
        List<MessageObject> historyMsg = requestHandler.getHistoryMsg();
        ResultMessage resultMessage = new ResultMessage(
                historyMsg.get(historyMsg.size() - 1).getContent()
                ,singleResult
        );
        allMessage.add(resultMessage);


        // 结果数据加入请求体中,确保会话连贯
        requestHandler.setResultMessageObject(new MessageObject("assistant",singleResult));

        return new ResponseResult(singleResult,allMessage,rawResult);

    }

    // String body = "{\"model\": \"gpt-3.5-turbo\",\"messages\": [{ \"role\": \"user\", \"content\": \"你是谁？\" }]}";
    private String getRequestBodyString(RequestHandler requestHandler) {
        // 数据封装
        RequestObject requestObject = new RequestObject();
        requestObject.setModel(requestHandler.getModel());
        requestObject.setMessages(requestHandler.getHistoryMsg());
        requestObject.setMax_tokens(requestHandler.getMaxTokens());
        // 转为JSON
        return JSON.toJSONString(requestObject);
    }
}
